<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 合可被 K 整除的子数组 -->
    <script>
      /*
       算出所有前缀和对k取余
      如果相同则可以相减，剩下那段就是子数组，前面相同的数量都可以记录进符合条件子数组数量
      所以用hashMap存储 前缀和对k取余结果的数量
      前缀和对k取余结果结果为负数时，加上k
      */
      var subarraysDivByK = function (nums, k) {
        let count = 0
        let map = new Array(k).fill(0)
        let sum = 0
        for (let i = 0; i < nums.length; i++) {
          sum += nums[i]
          let n = sum % k
          if (n < 0) n += k
          count += map[n]
          map[n] = map[n] + 1
        }
        return count + map[0]
      }
      console.log(subarraysDivByK([4, 5, 0, -2, -3, 1], 5))
    </script>
  </body>
</html>
